#import "FlutterCjadsdkPlugin.h"
#if __has_include(<flutter_cjadsdk_plugin/flutter_cjadsdk_plugin-Swift.h>)
#import <flutter_cjadsdk_plugin/flutter_cjadsdk_plugin-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "flutter_cjadsdk_plugin-Swift.h"

#endif

// 初始化方法
#define adSdkSetup              @"cjsdksetup"
// 开屏
#define splashAdMethod          @"getSplashAdMethod"
// 激励视频
#define rewardVideoAdMethod     @"getRewardVideoMethod"
// 全屏视频
#define fullscreenVideoAdMethod @"getFullscreenVideoMethod"
// 信息流
#define nativeAdMethod @"getNativeAdMethod"
// banner
#define bannerAdMethod @"getBannerAdMethod"
// 插屏
#define interstitialAdMethod @"getInterstitialAdMethod"
// 短视频
#define shortVideoAdMethod   @"getShortVideoAdMethod"

@interface FlutterCjadsdkPlugin()

@property (nonatomic, strong) CJSplashAd *splashAd;
@property (nonatomic, strong) CJRewardVideoAd *rewardVideoAd;
@property (nonatomic, strong) CJFullscreenVideoAd *fullscreenVideoAd;
@property (nonatomic, strong) CJInterstitialAd *interstitialAd;

@end

static FlutterCjadsdkPlugin *plugin = nil;

@implementation FlutterCjadsdkPlugin

+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        plugin = [[self alloc] init];
    });
    return plugin;
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    [FlutterCjadsdkPlugin shareInstance].methodChannel = [FlutterMethodChannel methodChannelWithName:@"flutter_cjadsdk_plugin" binaryMessenger:[registrar messenger]];
     [registrar addMethodCallDelegate:[FlutterCjadsdkPlugin shareInstance] channel:[FlutterCjadsdkPlugin shareInstance].methodChannel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *advertId = call.arguments[@"advertId"];
    NSString *configId = call.arguments[@"configId"];
    NSString *userId = call.arguments[@"userId"];
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    if (!window) {
        window = UIApplication.sharedApplication.windows.firstObject;
    }
    if ([call.method isEqualToString:adSdkSetup]) {
        [self.methodChannel invokeMethod:@"setupSuccess" arguments:@{@"message": @"开始初始化"}];
        if (configId.length > 0) {
            // 开始初始化
            [CJADManager configure: configId];
            [CJADManager openDebugLog];
            return;
        }
        [self.methodChannel invokeMethod:@"setupSuccess" arguments:@{@"message": @"初始化失败"}];
    }
    if ([call.method isEqualToString:splashAdMethod]) {
        CJSplashAd *splashAd = [[CJSplashAd alloc] initWithResourceId:advertId window:window rootViewController:window.rootViewController customLogoView: [UIView new]];
        splashAd.delegate = self;
        [splashAd loadAdData];
        self.splashAd = splashAd;
    } else if ([call.method isEqualToString:rewardVideoAdMethod]) {
        CJRewardVideoAd *rewardVideoAd = [[CJRewardVideoAd alloc] initWithResourceId:advertId userId:userId extend:@"" verificationMode:0];
        rewardVideoAd.delegate = self;
        [rewardVideoAd loadAdData];
        self.rewardVideoAd = rewardVideoAd;
    } else if ([call.method isEqualToString:fullscreenVideoAdMethod]) {
        CJFullscreenVideoAd *fullscreen = [[CJFullscreenVideoAd alloc] initWithResourceId:advertId];
        fullscreen.delegate = self;
        [fullscreen loadAdData];
        self.fullscreenVideoAd = fullscreen;
    } else if ([call.method isEqualToString:nativeAdMethod]) {
        [self.methodChannel invokeMethod:@"unkonw-support" arguments:@{@"message": @"暂不支持"}];
    } else if ([call.method isEqualToString:bannerAdMethod]) {
        [self.methodChannel invokeMethod:@"unkonw-support" arguments:@{@"message": @"暂不支持"}];
    } else if ([call.method isEqualToString:interstitialAdMethod]) {
        CJInterstitialAd *interstitialAd = [[CJInterstitialAd alloc] initWithResourceId:advertId];
        interstitialAd.delegate = self;
        [interstitialAd loadAdData];
        self.interstitialAd = interstitialAd;
    } else if ([call.method isEqualToString:shortVideoAdMethod]) {
        UIViewController *videoVC = [ShortViewController new];
        UIViewController *currentVC = [self getCurrentVC];
        videoVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [currentVC presentViewController:videoVC animated:true completion:nil];
    } else {
        // 未知
        [self.methodChannel invokeMethod:@"unkonw" arguments:@{@"message": @"未知事件"}];
    }
}

+ (UIWindow *)getCurrentWindow {
    UIWindow *window = UIApplication.sharedApplication.delegate.window;
    if (!window) {
        window = UIApplication.sharedApplication.windows.firstObject;
    }
    return window;
}

- (UIViewController *)getCurrentVC
{
    UIViewController*result =nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray*windows = [[UIApplication sharedApplication] windows];
        for(UIWindow* tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }

    //从根控制器开始查找
    UIViewController*rootVC = window.rootViewController;
    id nextResponder = [rootVC.view nextResponder];
    if([nextResponder isKindOfClass:[UINavigationController class]]) {
        result = ((UINavigationController*)nextResponder).topViewController;
        if([result isKindOfClass:[UITabBarController class]]) {
            result = ((UITabBarController*)result).selectedViewController;
        }
        
    } else if([nextResponder isKindOfClass:[UITabBarController class]]) {
        result = ((UITabBarController*)nextResponder).selectedViewController;
            if([result isKindOfClass:[UINavigationController class]]) {
                result = ((UINavigationController*)result).topViewController;
            }
        
    } else if([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
                    if([result isKindOfClass:[UINavigationController class]]) {
                        result = ((UINavigationController*)result).topViewController;
                        if([result isKindOfClass:[UITabBarController class]]) {
                            result = ((UITabBarController*)result).selectedViewController;
                        }
                    }
        else if([result isKindOfClass:[UIViewController class]]) {
            result = nextResponder;
        }
    }
    return result;
}
 
#pragma mark CJSplashAdDelegate
- (void)splashAdDidLoad:(CJSplashAd *)splashAd resourceId:(NSString *)resourceId {
    [splashAd showSplashAdToWindow:[FlutterCjadsdkPlugin getCurrentWindow]];
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"splashAdLoadSuccess" arguments:@{@"message": @"加载成功"}];
}

- (void)splashAdLoadFailed:(CJSplashAd *)splashAd error:(NSError *)error {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"splashAdLoadFailed" arguments:@{@"message": error.description}];
}

- (void)splashAdOnClicked:(CJSplashAd *)splashAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"splashAdClickEvent" arguments:@{@"message": @"点击事件"}];
}

- (void)splashAdOnClosed:(CJSplashAd *)splashAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"splashAdCloseEvent" arguments:@{@"message": @"关闭事件"}];
}

#pragma mark CJRewardVideoAdDelegate

// 达到奖励条件

- (void)rewardVideoOnRewarded:(CJRewardVideoAd *)rewardAd requestId:(NSString *)requestId {
    // 获得奖励
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"rewardVideoAdBeRewarded" arguments:@{@"message": @"Server validates successfully"}];
}

// 加载成功
- (void)rewardVideoAdDidLoad:(CJRewardVideoAd *)rewardAd resourceId:(NSString *)resourceId {
    [rewardAd showFromRootViewController: [self getCurrentVC]];
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"rewardVideoAdLoadSuccess" arguments:@{@"message": @"加载成功"}];
}

// 加载失败
- (void)rewardVideoAdLoadFailed:(CJRewardVideoAd *)rewardAd error:(NSError *)error {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"rewardVideoAdLoadFailed" arguments:@{@"message": error.description}];
}

// 点击
- (void)rewardVideoAdOnClicked:(CJRewardVideoAd *)rewardAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"rewardVideoAdClickEvent" arguments:@{@"message": @"点击事件"}];
}

// 关闭
- (void)rewardVideoAdOnClosed:(CJRewardVideoAd *)rewardAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"rewardVideoAdCloseEvent" arguments:@{@"message": @"关闭事件"}];
}

#pragma mark CJFullscreenVideoAdDelegate
- (void)fullscreenVideoAdDidLoad:(CJFullscreenVideoAd *)fullscreenAd resourceId:(NSString *)resourceId {
    [fullscreenAd showFromRootViewController: [self getCurrentVC]];
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"fullscreenVideoAdLoadSuccess" arguments:@{@"message": @"加载成功"}];
}

- (void)fullscreenVideoAdLoadFailed:(CJFullscreenVideoAd *)fullscreenAd error:(NSError *)error {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"fullscreenVideoAdLoadFailed" arguments:@{@"message": error.description}];
}

- (void)fullscreenVideoAdOnClicked:(CJFullscreenVideoAd *)fullscreenAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"fullscreenVideoAdClickEvent" arguments:@{@"message": @"点击事件"}];
}

- (void)fullscreenVideoAdOnClosed:(CJFullscreenVideoAd *)fullscreenAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"fullscreenVideoAdCloseEvent" arguments:@{@"message": @"关闭事件"}];
}

#pragma mark CJInterstitialAdDelegate
- (void)interstitialAdDidLoad:(CJInterstitialAd *)interstitialAd resourceId:(NSString *)resourceId {
    [interstitialAd showFromRootViewController:[self getCurrentVC]];
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"interstitialAdLoadSuccess" arguments:@{@"message": @"加载成功"}];
}

- (void)interstitialAdLoadFailed:(CJInterstitialAd *)interstitialAd error:(NSError *)error {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"interstitialAdLoadFailed" arguments:@{@"message": error.description}];
}

- (void)interstitialAdOnClicked:(CJInterstitialAd *)interstitialAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"interstitialAdClickEvent" arguments:@{@"message": @"点击事件"}];
}

- (void)interstitialAdOnClosed:(CJInterstitialAd *)interstitialAd {
    [[FlutterCjadsdkPlugin shareInstance].methodChannel invokeMethod:@"interstitialAdCloseEvent" arguments:@{@"message": @"关闭事件"}];
}

@end

